package com.qk.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import com.qk.aop.anno.LogRecord;
import com.qk.common.Result;
import com.qk.enums.ApiEnum;
import com.qk.exception.CommonException;
import com.qk.util.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/08 15:42
 * @Description: 文件处理控制器
 */
@RestController
@Slf4j
@SuppressWarnings("all")
public class FileHandleController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @LogRecord
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("image") MultipartFile multipartFile) {
        // 文件空值校验
        if (ObjectUtil.isNull(multipartFile) || multipartFile.isEmpty()) {
            log.warn("上传文件为空");
            CommonException.throwException(ApiEnum.UPLOAD_EMPTY_ERROR);
        }

        try {
            log.info("上传图片开始：{}", multipartFile);
            String objectName = StrBuilder.create()
                    .append(UUID.randomUUID())
                    .append(".")
                    .append(FileNameUtil.extName(multipartFile.getOriginalFilename()))
                    .toString();
            String url = aliyunOSSOperator.uploadFile(multipartFile.getBytes(), objectName);
            if(ObjectUtil.isNull(url)) {
                CommonException.throwException(ApiEnum.UPLOAD_IMAGE_ERROR);
            }
            log.info("上传图片成功：{}", url);
            return Result.success(url);
        } catch (Exception e) {
            log.error("上传图片失败：{}", e.getMessage());
            CommonException.throwException(ApiEnum.UPLOAD_IMAGE_ERROR);
        }
        return Result.error();
    }
}
